package com.zy.edu.service.impl;

import com.zy.edu.bean.*;
import com.zy.edu.config.SystemParam;
import com.zy.edu.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: HuangHaiShui
 * @description:
 * @date: 2021/8/24 16:50
 * @version: 1.0
 */
@Service
@Transactional
public class StatsServiceImpl {

    @Resource
    UserService userService;

    @Resource
    SchoolService schoolService;

    @Resource
    ClassinfoService classinfoService;
    @Resource
    CourseService courseService;
    @Resource
    CourseChapterService courseChapterService;
    @Resource
    CourseChapterClassService courseChapterClassService;
    @Resource
    CourseChapterSignService courseChapterSignService;

    @Resource
    CourseChapterHomeworkStuService courseChapterHomeworkStuService;
    @Resource
    CourseChapterExercisesStuService courseChapterExercisesStuService;

    @Resource
    LogService logService;

    public Map analysis(InputParam inputParam) {

        if(StringUtils.isEmpty(inputParam.getUserId())){
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }

        StatsInfo statsInfo = new StatsInfo();
        DecimalFormat decimalFormat= new  DecimalFormat( "0.00" );
        User currentUser = userService.selectById(inputParam.getUserId());

        if(currentUser.getRoleType().equals(Role.SCHOOL)){
            inputParam.setSchoolId(currentUser.getSchoolId());
            //学生总数
            Integer userData = userService.getCountByParam(inputParam);
            statsInfo.setStus(userData);
            //班级总数
            List<Classinfo> classinfoList = classinfoService.getByParam(inputParam);
            statsInfo.setCls(classinfoList.size());
            //学生出勤率
            float attendance=0.0f;
            //作业完成率
            float homework=0.0f;
            for (Classinfo classinfo : classinfoList) {
                //查询出班级里的学生总数
                Integer temp = userService.getCountByClassId(classinfo.getId());
                //若班级无学生则，跳出
                if(temp==0) {continue;}
                attendance += computeAttendence(classinfo.getId(),temp);
                homework += computeHome(classinfo.getId());
            }
            attendance = attendance/classinfoList.size();
            homework= homework/classinfoList.size();
            // 学生出勤率,保留两位小数
            statsInfo.setAttendanceRate(decimalFormat.format(attendance));
            // 作业完成率,保留两位小数
            statsInfo.setHomeworkRate(decimalFormat.format(homework));

            //作业完成率
        }else if(currentUser.getRoleType().equals(Role.TEACHER)){
            //教师的统计需要额外处理
            inputParam.setSchoolId(currentUser.getSchoolId());
            //班级总数
            List<Classinfo> classinfoList = classinfoService.findByUserId(inputParam.getUserId());
            statsInfo.setCls(classinfoList.size());
            //学生总数,遍历班级，累加学生数量
            Integer stuTotal=0;
            float attendance=0.0f;
            //作业完成率
            float homework=0.0f;
            for (Classinfo classinfo : classinfoList) {
                //查询出班级里的学生总数
                Integer temp = userService.getCountByClassId(classinfo.getId());
                //若班级无学生则，跳出
                if(temp==0) {continue;}
                stuTotal+=temp;
                attendance += computeAttendence(classinfo.getId(),temp);
                homework += computeHome(classinfo.getId());
            }
            attendance = attendance/classinfoList.size();
            homework= homework/classinfoList.size();

            statsInfo.setStus(stuTotal);
            // 学生出勤率,保留两位小数
            statsInfo.setAttendanceRate(decimalFormat.format(attendance));
            // 作业完成率,保留两位小数
            statsInfo.setHomeworkRate(decimalFormat.format(homework));
        }else if(currentUser.getRoleType().equals(Role.AREA)){
            //区管展示 学校总数、学生总数、月登录数据
            inputParam.setJurisId(currentUser.getJurisId());
            //每月登录数据
            Integer loginData = logService.statsByJurisId(inputParam);
            statsInfo.setLoginData(loginData);
            //学校总数
            Integer schoolData = schoolService.getCountByParam(inputParam);
            statsInfo.setSchools(schoolData);
            //学生总数
            Integer userData = userService.getCountByParam(inputParam);
            statsInfo.setStus(userData);


        }else if(currentUser.getRoleType().equals(Role.STUDENT)){
            //学生的学习时长统计
            statsInfo.setCourseList(getStuCourseStats(currentUser));
            //评价详情
            statsInfo.setStatsAbility(courseChapterHomeworkStuService.getAbility(currentUser.getId()));
            //习题正确率
            String exerciseRate = courseChapterExercisesStuService.getExerciseRate(currentUser.getId());
            statsInfo.setExerciseRate(exerciseRate);
        }

        return ResponseInfo.success(statsInfo);
    }

    /**
     * @Author: HuangHaiShui
     * @Description: 计算班级的出勤率
     * @Date: 8:32 2021/9/4
     * @param clsId:  班级id
     * @param stuTotal:   该班级的学生总数
     * @return: float
     **/
    private float computeAttendence(String clsId,int stuTotal){
        //查出每个班级的出勤率
        //course_chapter_class表查出每个班级老师已上过的课时
        Integer teaChapter = courseChapterClassService.getCountByParam(clsId);
        //查询班级学生已签到的课时
        Integer stuChapter =courseChapterSignService.getCountByParam(clsId);
        //计算单个班级的出勤率
        if(teaChapter==null || teaChapter==0){
             return 0;
        }else {
            float attendanceTemp = Float.valueOf(stuChapter) / (teaChapter * stuTotal);
            return attendanceTemp;
        }
    }

    //计算作业完成率
    private float computeHome(String clsId){
        //查询每个班级已布置的所有作业
        int homeTotal = courseChapterHomeworkStuService.countByClsId(clsId, false,null,false);
        //查询每个班级已完成的所有作业
        int homeSub = courseChapterHomeworkStuService.countByClsId(clsId, true,null,false);
        if(homeTotal==0){
            return 0;
        }else {
            float homeworkTemp = Float.valueOf(homeSub) /homeTotal;
            return homeworkTemp;
        }
    }

    private List<StatsCourse> getStuCourseStats(User user){
        List<StatsCourse> list = new ArrayList<>();
        //先查出该学生的所有课程
        List<Course> courseList = courseService.getByClsId(user.getClassId());
        for (Course course : courseList) {
            StatsCourse sc = new StatsCourse();
            sc.setName(course.getName());
            //查出该课程的所有课时
            int total = courseChapterService.countByCourseId(course.getId());
            sc.setTotal(total);
            //查出该课程学生签到的课时
            int signTotal = courseChapterSignService.getCountByCourseAndStuId(user.getId(),course.getId());
            sc.setSign(signTotal);
            list.add(sc);
        }
        return list;
    }



}
